package com.wooming.studentinfosystem.controller;

import com.wooming.studentinfosystem.dto.StudentInfoDTO;
import com.wooming.studentinfosystem.entity.Student;
import com.wooming.studentinfosystem.service.impl.StudentAddService;
import com.wooming.studentinfosystem.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller层: 学生信息添加
 *
 * @author wooming
 */
@RestController
@RequestMapping("/api/students")
public class StudentAddController {

    @Autowired
    private StudentAddService studentAddService;

    @PostMapping
    public Result<Void> addStudent(@RequestBody StudentInfoDTO params) {
        // 测试用代码:score字段是否成功注入
//        params.getScores().forEach((key, value) -> System.out.println(key + ":" + value));

        // 验证参数
        if(params.getStudentId() == null || params.getStudentId().isEmpty()
                || params.getName() == null || params.getName().isEmpty()
                || params.getAge() == null || params.getAge() < 0
                || params.getGender() == null || params.getGender().isEmpty()
                || params.getClassNum() == null || params.getClassNum().isEmpty()
                || params.getType() == null || params.getType().isEmpty()
                || params.getProvince() == null || params.getProvince().isEmpty()
                || params.getCity() == null || params.getCity().isEmpty()
                || params.getStreet() == null || params.getStreet().isEmpty()
                || params.getDoorNumber() == null || params.getDoorNumber().isEmpty()
                || params.getScores() == null || params.getScores().isEmpty()
        ){
            return Result.error(400, "必要参数缺少");
        } else if (params.getType().equals("UNDERGRAD") && (params.getMajor() == null || params.getMajor().isEmpty())) {
            return Result.error(400, "必要参数缺少");
        } else if (params.getType().equals("GRADUATE") && (params.getSupervisor() == null || params.getSupervisor().isEmpty()
                || params.getResearchFiled() == null || params.getResearchFiled().isEmpty())) {
            return Result.error(400, "必要参数缺少");
        }

        // 判断学号是否已存在
        if(studentAddService.isStudentIdExists(params.getStudentId())) {
            return Result.error(400, "学号已存在");
        }

        // 将DTO转换为实体对象并添加到数据库中
        Student student = studentAddService.convertToEntity(params);
        // 测试用代码:参数是否成功封装为实体类
//        student.getScores().forEach((key, value) -> System.out.println(key + ":" + value));
        studentAddService.addStudent(student);
        return Result.success(null);
    }
}
